<template>
  <el-form
    ref="form"
    :model="form"
    :rules="formRules"
    :size="get(option, 'formSize', defaultFormSize)"
    :label-position="get(option,'labelPosition','top')"
    :validate-on-rule-change="false"

    @submit.native.prevent
  >
    <el-row :gutter="20" :span="24">
      <el-col
        v-for="column in formColumn"
        :key="column.label"
        :md="column.span || 24"
        :sm="12"
        :xs="24"
      >
        <el-form-item
          :label="column.label?`${column.label}:`:''"
          :prop="column.prop"
          :label-width="get(column, 'labelWidth', column.labelWidth || defaultLabelWidth)"
          :style="{
            height: get(column, 'labelHeight', column.labelHeight || defaultLabelHeight)
          }"
        >
          <!-- 自定义表单项内容 -->
          <slot
            v-if="column.slotName"
            :name="column.slotName"
            :form="form"
            :prop="column.prop"
            :value="form[column.prop]"
          />
          <!-- 其他表单项 -->
          <div
            :is="get(column, 'type', 'el-input')"
            v-else
            v-model="form[column.prop]"
            clearable
            style="width: 100%"
            range-separator="-"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :placeholder="getPlaceholder(column.type, column.label)"
            :label-width="get(column, 'size', column || defaultFormSize)"
            :disabled="get(column, 'disabled', false)"
            :row="get(column,'attr.row',2)"
            :type="get(column,'attr.type','daterange')"
            :format="get(column,'attr.format')"
            :value-format="get(column,'attr.valueFormat')"
            :picker-options="get(column,'attr.pickerOptions')"
            @change="(val)=>{
              column.type==='el-date-picker'&& $emit('timeChange',val)
            }"
          >
            <template v-if="column.type == 'el-select'">
              <el-option
                v-for="item in column.dic"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </template>
            <template v-if="column.type == 'el-radio-group'">
              <el-radio
                v-for="item in column.dic"
                :key="item.value"
                :label="item.label"
              >
                {{ item.value }}
              </el-radio>
            </template>
            <template v-if="column.type == 'el-checkbox-group'">
              <el-checkbox
                v-for="item in column.dic"
                :key="item.label"
                :label="item.value"
              >
                {{ item.label }}
              </el-checkbox>
            </template>
          </div>
        </el-form-item>
        <!-- 自定义表单项后面的插槽 -->
      </el-col>
    </el-row>
    <!-- 自定义表单底部插槽 -->
    <slot name="footer" :form="form" />
  </el-form>
</template>
<script>
import get from 'lodash/get'
import request from '@/utils/request'
export default {
  props: {
    option: {
      type: Object,
      default: () => {}
    },
    form: {
      type: Object,
      default: () => {}
    }
  },
  data() {
    return {
      formRules: {},
      defaultFormSize: 'small',
      defaultLabelWidth: '90px',
      defaultLabelHeight: '50px'
    }
  },
  computed: {
    formColumn() {
      return this.option.column
    }
  },
  created() {
    this.initRules()
    this.initRequest()
    this.initValue()
  },
  methods: {
    get,
    getPlaceholder(type, label) {
      return type === 'el-select' ? `请选择${label}` : `请输入${label}`
    },
    initRequest() {
      if (!Array.isArray(this.formColumn)) return
      const urls = this.formColumn?.filter((item) => item.url && item.url.indexOf('/park') === 0) || []
      urls.forEach(async(item) => {
        const params = { ...item.requestParams }
        // 请求的方法和接收的数据，和后台商量来写
        const res = await request({
          url: item.url,
          method: 'get',
          params
        }) || []
        // 整理数据
        const finalResult = res.map((result) => ({
          label: result[item.requestLabel],
          value: result[item.requestValue]
        }))
        // set数据
        this.$set(item, 'dic', finalResult)
      })
    },
    initRules() {
      if (!Array.isArray(this.formColumn)) return
      this.formColumn?.forEach((item) => {
        if (item.rules) {
          item.rules.map((rule, index) => {
            // 生成必填项的校验规则
            if (rule.required) {
              item.rules.splice(index, 1, {
                message: ['el-radio-group', 'el-checkbox-group'].includes(item.type) ? item.label + '必选' : item.label + '必填',
                ...rule
              })
            }
          })
          // 添加校验规则
          this.$set(this.formRules, item.prop, item.rules)
        }
      })
    },
    initValue() {
      const selectList = this.formColumn.filter((item) => ['el-radio-group', 'el-checkbox-group'].includes(item.type))
      // 设置radio和checkbox默认第一个值选中
      selectList.forEach((item) => {
        this.$set(this.form, item.prop, item.type === 'el-radio-group' ? item.dic[0].label : [item.dic[0].value])
      })
    },
    resetFields() {
      this.$refs.form.resetFields()
    },
    async validate() {
      await this.$refs.form.validate()
      return Promise.resolve(true)
    }

  }

}
</script>
<style lang="scss" scoped>

 .el-form--label-top ::v-deep .el-form-item__label {
    float: none;
    display: inline-block;
    text-align: left;
    margin-top: 10px;
    padding: 0px !important;
}
</style>
